package com.gitee.liuzhi.framework.starter.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.io.StringReader;
import java.util.Map;

/**
 * Created by 2022/4/21/0021
 *
 * @author LiuZhi
 * @version V1.0
 * @description: FreeMarker 模板引擎工具类
 */
public class FreeMarkerUtils {

    private static final Configuration FREE_MARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_0);

    static {
        FREE_MARKER_CONFIGURATION.setDefaultEncoding("UTF-8");
        FREE_MARKER_CONFIGURATION.setNumberFormat("#");
        FREE_MARKER_CONFIGURATION.setClassicCompatible(true);
    }

    /**
     * 模板替换方法
     *
     * @param templateStr 原字符串
     * @param dataModel   替换字段内容集合
     * @return 替换后的字符串
     */
    public static String rendering(String templateStr, Map<String, Object> dataModel) {
        try {
            Template template = new Template(templateStr, new StringReader(templateStr), FREE_MARKER_CONFIGURATION);
            return FreeMarkerTemplateUtils.processTemplateIntoString(template, dataModel);
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}
